﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;

namespace Common
{
    public class StringHelper
    {
        // Methods
        private static char ConvertDbcToSbcChar(char c)
        {
            byte[] bytes = Encoding.Unicode.GetBytes(c.ToString());
            int num = Convert.ToInt32(bytes[1]);
            int num2 = Convert.ToInt32(bytes[0]);
            int num3 = (num * 0x100) + num2;
            if ((num3 >= 0xff01) && (num3 <= 0xff5e))
            {
                int num4 = num3 - 0xfee0;
                byte num5 = Convert.ToByte(num4);
                bytes[0] = num5;
                bytes[1] = 0;
            }
            else if (num3 == 0x3000)
            {
                int num6 = 0x20;
                byte num7 = Convert.ToByte(num6);
                bytes[0] = num7;
                bytes[1] = 0;
            }
            else
            {
                return c;
            }
            return Convert.ToChar(Encoding.Unicode.GetString(bytes));
        }

        public static string ConvertDbcToSbcString(string source)
        {
            StringBuilder builder = new StringBuilder();
            char[] chArray = source.ToCharArray();
            for (int i = 0; i < chArray.Length; i++)
            {
                builder.Append(ConvertDbcToSbcChar(chArray[i]));
            }
            return builder.ToString();
        }

        public static string ConvertEncoding(Encoding dstEncoding, string s)
        {
            return ConvertEncoding(Encoding.Default, dstEncoding, s);
        }

        public static string ConvertEncoding(Encoding srcEncoding, Encoding dstEncoding, string s)
        {
            byte[] bytes = Encoding.Default.GetBytes(s);
            bytes = Encoding.Convert(srcEncoding, dstEncoding, bytes);
            return Encoding.Default.GetString(bytes);
        }

        public static string ConvertStringArrayToStrings(string[] strArray)
        {
            if (strArray == null)
            {
                return "";
            }
            string str = "";
            for (int i = 0; i < strArray.Length; i++)
            {
                str = str + strArray[i] + ",";
            }
            return str.TrimEnd(new char[] { ',' });
        }

        public static string FlashFilter(string htmlCode)
        {
            string pattern = @"\w*<OBJECT\s+.*(macromedia)[\s*|\S*]{1,1300}</OBJECT>";
            return Regex.Replace(htmlCode, pattern, "", RegexOptions.Multiline);
        }

        public static string FormatDoubleToPercent(double num)
        {
            double num2 = num * 100.0;
            return (num2.ToString("#0.00") + "%");
        }

        public static string GenerateRndNum(int intLength)
        {
            string[] strArray = "0,1,2,3,4,5,6,7,8,9".Split(new char[] { ',' });
            string str2 = "";
            int num = -1;
            Random random = new Random();
            for (int i = 1; i < (intLength + 1); i++)
            {
                if (num != -1)
                {
                    random = new Random((i * num) * ((int)DateTime.Now.Ticks));
                }
                int index = random.Next(strArray.Length);
                if ((num != -1) && (num == index))
                {
                    return GenerateRndNum(intLength);
                }
                num = index;
                str2 = str2 + strArray[index];
            }
            return str2;
        }

        public static string GetCurrentDateString()
        {
            DateTime now = DateTime.Now;
            string specialNumericString = GetSpecialNumericString(now.Month, 2);
            return (now.Year + specialNumericString + GetSpecialNumericString(now.Day, 2));
        }

        public static string GetHumanFriendDate(DateTime dt, bool isLongTime = true)
        {
            TimeSpan span = (TimeSpan)(DateTime.Now.Date.AddDays(1.0).AddMilliseconds(-1.0) - dt);
            TimeSpan span2 = (TimeSpan)(DateTime.Now - dt);
            switch (span.Days)
            {
                case 0:
                    if (span2.TotalMinutes > 0.0)
                    {
                        if (span2.TotalMinutes <= 1.0)
                        {
                            return (span2.Seconds + "秒钟前");
                        }
                        if (span2.TotalHours <= 1.0)
                        {
                            return (span2.Minutes + "分钟前");
                        }
                        return (span2.Hours + "小时前");
                    }
                    return "刚刚";

                case 1:
                    return dt.ToString("昨天 HH:mm");

                case 2:
                    return dt.ToString("前天 HH:mm");
            }
            if (!isLongTime)
            {
                return dt.ToString("MM-dd");
            }
            return dt.ToString("yyyy-MM-dd HH:mm");
        }

        public static int GetRealLength(string source)
        {
            return Encoding.Default.GetByteCount(source);
        }

        public static string GetSmallCurrentDateString()
        {
            return GetCurrentDateString().Substring(2);
        }

        public static string GetSpecialNumericString(int number, int length)
        {
            return number.ToString("d" + length);
        }

        public static bool IsEmptyString(string str)
        {
            if ((str != null) && (str.Length != 0))
            {
                return false;
            }
            return true;
        }

        public static string ReadHttp(string URL, ref string Content)
        {
            string str = "ERROR";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
            HttpWebResponse response = null;
            StreamReader reader = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
                str = response.StatusCode.ToString();
                reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("GB2312"));
                Content = reader.ReadToEnd();
            }
            catch
            {
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
                if (reader != null)
                {
                    reader.Close();
                }
            }
            return str;
        }

        public static string RemoveHtmlTag(string source)
        {
            return Regex.Replace(source, "<[^>]*>", "");
        }

        public static string SqlFilter(string source)
        {
            source = source.Replace("'", "''").Replace(";", "；").Replace("(", "（").Replace(")", "）");
            source = Regex.Replace(source, "select", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "insert", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "update", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "delete", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "drop", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "truncate", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "declare", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "xp_cmdshell", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "/add", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "net user", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "exec", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "execute", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "xp_", "x p_", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "sp_", "s p_", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "0x", "0 x", RegexOptions.IgnoreCase);
            return source;
        }

        public static string SubSpecialLengthDecimal(object objDecimal, int length)
        {
            return ConvertHelper.GetDecimal(objDecimal).ToString("f" + length);
        }

        public static string SubString(string source, int n, bool needEndDot)
        {
            string str = string.Empty;
            if (GetRealLength(source) <= n)
            {
                return source;
            }
            int num = 0;
            char[] chArray = source.ToCharArray();
            for (int i = 0; (i < chArray.Length) && (num < n); i++)
            {
                if (chArray[i] > '\x007f')
                {
                    str = str + chArray[i];
                    num += 2;
                }
                else
                {
                    str = str + chArray[i];
                    num++;
                }
            }
            if (needEndDot)
            {
                str = str + "...";
            }
            return str;
        }

        public static string TrimEndZeroForPrice(string price)
        {
            while (price.EndsWith("0") && (price.IndexOf(".") > 0))
            {
                price = price.TrimEnd(new char[] { '0' });
            }
            if (price.EndsWith("."))
            {
                price = price.Substring(0, price.Length - 1);
            }
            return price;
        }

        public static string TrimStartZero(string source)
        {
            while (source.StartsWith("0"))
            {
                source = source.Substring(1);
            }
            return source;
        }

        public static string UrlEncode(string s)
        {
            return UrlEncode(s, Encoding.Default);
        }

        public static string UrlEncode(string s, Encoding encoding)
        {
            StringBuilder builder = new StringBuilder();
            byte[] bytes = encoding.GetBytes(s);
            for (int i = 0; i < bytes.Length; i++)
            {
                builder.Append("%" + Convert.ToString(bytes[i], 0x10));
            }
            return builder.ToString();
        }

        public static string XSSFilter(string source)
        {
            Match match;
            if (source == "")
            {
                return source;
            }
            string input = HttpUtility.UrlDecode(source);
            string replacement = " onXXX =";
            string str3 = "";
            string pattern = "<[^<>]*>";
            string str5 = @"([\s]|[:])+[o]{1}[n]{1}\w*\s*={1}";
            string str6 = @"\s*((javascript)|(vbscript))\s*[:]?";
            string str7 = @"<([\s/])*script.*>";
            string str8 = @"<([\s/])*\S.+>";
            Regex regex = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
            Regex regex2 = new Regex(str5, RegexOptions.Compiled | RegexOptions.IgnoreCase);
            Regex regex3 = new Regex(str7, RegexOptions.Compiled | RegexOptions.IgnoreCase);
            Regex regex4 = new Regex(str6, RegexOptions.Compiled | RegexOptions.IgnoreCase);
            Regex regex5 = new Regex(str8, RegexOptions.Compiled | RegexOptions.IgnoreCase);
            for (match = regex.Match(input); match.Success; match = match.NextMatch())
            {
                str3 = match.Groups[0].Value;
                if (regex3.Match(str3).Success)
                {
                    str3 = regex3.Replace(str3, " ");
                    input = input.Replace(match.Groups[0].Value, str3);
                }
            }
            for (match = regex.Match(input); match.Success; match = match.NextMatch())
            {
                str3 = match.Groups[0].Value;
                if (regex2.Match(str3).Success)
                {
                    str3 = regex2.Replace(str3, replacement);
                    input = input.Replace(match.Groups[0].Value, str3);
                }
            }
            for (match = regex.Match(input); match.Success; match = match.NextMatch())
            {
                str3 = match.Groups[0].Value;
                if (regex4.Match(str3).Success)
                {
                    str3 = regex4.Replace(str3, " ");
                    input = input.Replace(match.Groups[0].Value, str3);
                }
            }
            for (Match match2 = regex2.Match(input); match2.Success; match2 = match2.NextMatch())
            {
                str3 = match2.Groups[0].Value;
                str3 = regex2.Replace(str3, replacement);
                input = input.Replace(match2.Groups[0].Value, str3);
            }
            for (Match match5 = regex5.Match(input); match5.Success; match5 = match5.NextMatch())
            {
                str3 = match5.Groups[0].Value;
                str3 = regex5.Replace(str3, "");
                input = input.Replace(match5.Groups[0].Value, str3);
            }
            return input;
        }
    }

}
